//
//  TodoModel.swift
//  ToDo4
//
//  Created by Jeyi Zhou on 2025/10/26.
//

import Foundation
import Combine

enum Quadrant: String, CaseIterable, Codable {
    case urgentImportant = "urgentImportant"
    case importantNotUrgent = "importantNotUrgent"
    case urgentNotImportant = "urgentNotImportant"
    case notUrgentNotImportant = "notUrgentNotImportant"
    
    var displayName: String {
        switch self {
        case .urgentImportant:
            return "紧急重要"
        case .importantNotUrgent:
            return "重要不紧急"
        case .urgentNotImportant:
            return "紧急不重要"
        case .notUrgentNotImportant:
            return "不紧急不重要"
        }
    }
    
    var colorName: String {
        switch self {
        case .urgentImportant:
            return "red"
        case .importantNotUrgent:
            return "orange"
        case .urgentNotImportant:
            return "yellow"
        case .notUrgentNotImportant:
            return "green"
        }
    }
}

struct TodoItem: Identifiable, Codable {
    let id = UUID()
    var title: String
    var description: String
    var quadrant: Quadrant
    var isCompleted: Bool
    var createdAt: Date
    var completedAt: Date?
    var updatedAt: Date
    
    init(title: String, description: String, quadrant: Quadrant) {
        self.title = title
        self.description = description
        self.quadrant = quadrant
        self.isCompleted = false
        self.createdAt = Date()
        self.updatedAt = Date()
    }
    
    mutating func toggleCompletion() {
        isCompleted.toggle()
        completedAt = isCompleted ? Date() : nil
        updatedAt = Date()
    }
}

// MARK: - 数据导入导出相关
struct ExportData: Codable {
    let version: String
    let exportDate: Date
    let appVersion: String
    let todos: [TodoItem]
}

struct ImportResult {
    let imported: Int
    let skipped: Int
    let errors: [String]
}

class TodoManager: ObservableObject {
    @Published var todos: [TodoItem] = []
    @Published var showAddTodo = false
    @Published var showEditTodo = false
    @Published var editingTodo: TodoItem?
    @Published var alertMessage = ""
    @Published var showAlert = false
    
    private let userDefaults = UserDefaults.standard
    private let todosKey = "savedTodos"
    
    init() {
        loadTodos()
    }
    
    func addTodo(_ todo: TodoItem) {
        todos.append(todo)
        saveTodos()
    }
    
    func deleteTodo(_ todo: TodoItem) {
        todos.removeAll { $0.id == todo.id }
        saveTodos()
    }
    
    func toggleTodoCompletion(_ todo: TodoItem) {
        if let index = todos.firstIndex(where: { $0.id == todo.id }) {
            todos[index].toggleCompletion()
            
            // 如果任务已完成，将其移动到象限底部
            if todos[index].isCompleted {
                let completedTodo = todos.remove(at: index)
                // 找到该象限中未完成任务的数量
                let incompleteCount = todos.filter { 
                    $0.quadrant == completedTodo.quadrant && !$0.isCompleted 
                }.count
                
                // 将完成的任务插入到该象限未完成任务之后
                let insertIndex = todos.firstIndex { 
                    $0.quadrant == completedTodo.quadrant && $0.isCompleted 
                } ?? todos.firstIndex { 
                    $0.quadrant.rawValue > completedTodo.quadrant.rawValue 
                } ?? todos.count
                
                todos.insert(completedTodo, at: insertIndex)
                showFeedback("任务已完成")
            } else {
                showFeedback("任务已重新激活")
            }
            
            saveTodos()
        }
    }
    
    func updateTodo(_ todo: TodoItem) {
        if let index = todos.firstIndex(where: { $0.id == todo.id }) {
            todos[index] = todo
            saveTodos()
        }
    }
    
    private func saveTodos() {
        if let encoded = try? JSONEncoder().encode(todos) {
            userDefaults.set(encoded, forKey: todosKey)
        }
    }
    
    private func loadTodos() {
        if let data = userDefaults.data(forKey: todosKey),
           let decoded = try? JSONDecoder().decode([TodoItem].self, from: data) {
            todos = decoded
        }
    }
    
    func getTodosForQuadrant(_ quadrant: Quadrant) -> [TodoItem] {
        return todos.filter { $0.quadrant == quadrant }
    }
    
    func showFeedback(_ message: String) {
        alertMessage = message
        showAlert = true
    }
    
    func startEditTodo(_ todo: TodoItem) {
        editingTodo = todo
        showEditTodo = true
    }

    // 简单的导出功能
    func exportAllTodos() -> String? {
        let formatter = ISO8601DateFormatter()

        let exportData: [String: Any] = [
            "version": "1.0",
            "exportDate": formatter.string(from: Date()),
            "todos": todos.map { todo in
                [
                    "title": todo.title,
                    "description": todo.description,
                    "quadrant": todo.quadrant.rawValue,
                    "isCompleted": todo.isCompleted,
                    "createdAt": formatter.string(from: todo.createdAt),
                    "updatedAt": formatter.string(from: todo.updatedAt)
                ]
            }
        ]

        do {
            let jsonData = try JSONSerialization.data(withJSONObject: exportData, options: .prettyPrinted)
            return String(data: jsonData, encoding: .utf8)
        } catch {
            print("导出失败: \(error)")
            return nil
        }
    }

    // 导入功能
    func importTodos(from jsonString: String) -> ImportResult {
        var imported = 0
        var skipped = 0
        var errors: [String] = []

        guard let jsonData = jsonString.data(using: .utf8) else {
            errors.append("无效的UTF-8编码")
            return ImportResult(imported: imported, skipped: skipped, errors: errors)
        }

        do {
            guard let importData = try JSONSerialization.jsonObject(with: jsonData) as? [String: Any] else {
                errors.append("无效的JSON格式")
                return ImportResult(imported: imported, skipped: skipped, errors: errors)
            }

            // 检查版本
            if let version = importData["version"] as? String, version != "1.0" {
                errors.append("不支持的版本: \(version)")
            }

            guard let todosArray = importData["todos"] as? [[String: Any]] else {
                errors.append("找不到todos数据")
                return ImportResult(imported: imported, skipped: skipped, errors: errors)
            }

            let formatter = ISO8601DateFormatter()

            for todoDict in todosArray {
                do {
                    // 解析必需字段
                    guard let title = todoDict["title"] as? String,
                          let description = todoDict["description"] as? String,
                          let quadrantRaw = todoDict["quadrant"] as? String,
                          let quadrant = Quadrant(rawValue: quadrantRaw),
                          let isCompleted = todoDict["isCompleted"] as? Bool else {
                        errors.append("缺少必需字段或格式错误")
                        skipped += 1
                        continue
                    }

                    // 解析日期
                    let createdAt: Date
                    let updatedAt: Date
                    let completedAt: Date?

                    if let createdAtString = todoDict["createdAt"] as? String,
                       let date = formatter.date(from: createdAtString) {
                        createdAt = date
                    } else {
                        createdAt = Date()
                    }

                    if let updatedAtString = todoDict["updatedAt"] as? String,
                       let date = formatter.date(from: updatedAtString) {
                        updatedAt = date
                    } else {
                        updatedAt = Date()
                    }

                    if let completedAtString = todoDict["completedAt"] as? String,
                       let date = formatter.date(from: completedAtString) {
                        completedAt = date
                    } else {
                        completedAt = nil
                    }

                    // 创建新的TodoItem
                    var newTodo = TodoItem(title: title, description: description, quadrant: quadrant)
                    newTodo.isCompleted = isCompleted
                    newTodo.createdAt = createdAt
                    newTodo.updatedAt = updatedAt
                    newTodo.completedAt = completedAt

                    // 检查是否已存在相同的任务（基于ID或内容）
                    let isDuplicate = todos.contains { existing in
                        existing.title == title &&
                        existing.description == description &&
                        existing.quadrant == quadrant
                    }

                    if isDuplicate {
                        skipped += 1
                    } else {
                        todos.append(newTodo)
                        imported += 1
                    }

                } catch {
                    errors.append("解析任务时出错: \(error.localizedDescription)")
                    skipped += 1
                }
            }

            if imported > 0 {
                saveTodos()
            }

        } catch {
            errors.append("JSON解析失败: \(error.localizedDescription)")
        }

        return ImportResult(imported: imported, skipped: skipped, errors: errors)
    }
}
